{% extends 'base.html' %}
{% load static %}

{% block title%}Add a New Book | {{ block.super}}{% endblock %}
{% block head_extra %}
<link rel="stylesheet" href="{% static 'css/main.css' %}">
<link rel="stylesheet" href="{% static 'css/map-style.css' %}">
<link rel="stylesheet" href="{% static 'css/leaflet-search.css' %}">

<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>

<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin=""></script>

<!-- Bootstrap Datepicker -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

<!-- Mapbox -->
<script src='https://api.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.44.1/mapbox-gl.css' rel='stylesheet' />

<!-- jQuery UI -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />

{% endblock head_extra %}

{% block content %}

<div class="container">
    <h1>New Book</h1>
    <p>Add a new book here:</p>
    {% for key, value in form.errors.items %}
        <div style="color:red;">{{ key }}: {{ value }}</div>
    {% endfor %}
    <form method="POST" action="{% url 'books:new' %}">
        {% csrf_token %}
        
        <div class="row">
            <div class="col-md-9">
                    {{ form.title }}
            </div>

            <div class="col-md-3">
                    {{ form.publish_date }}
            </div>
        </div>
        
        <hr>
        {{ form.synopsis }}
        <hr>
        {{ form.pages }}
        <hr>
        <div class="row">
            <div class="col-md-6">
                {{ form.lon }}
            </div>
            <div class="col-md-6">
                {{ form.lat }}
            </div>
        </div>

        <div id="mapid"></div>
        <hr>
        <div class="row" id="authors">
            <div class="col-md-8">
                {{ form.author }}
            </div>
            <div class="col-md-4">
                <a class="btn btn-warning add-author" id="add-author">Add another author</a>
            </div>
        </div>

        <script>

            $(document.body).on('click', '.remove-author', function(){
                console.log('removing author')
                $(this).parent().prev().remove()
                $(this).parent().remove()
                
            })

            $(document.body).on('keydown.autocomplete', '.add-author-input', function(){
                $(this).autocomplete({
                    source: "/authors/search_authors/",
                    minLength: 2,
                })
            })

            $(document.body).on('click', '.add-author', function(){
                console.log('adding button')
                $(this).parent().after(
                    "<div class='col-md-8'> \
                        <input class='form-control add-author-input' name='author' placeholder='add another author'/>\
                    </div> \
                    <div class='col-md-4'> \
                        <a class='btn btn-default remove-author'>❌</a>\
                        <a class='btn btn-warning add-author' id='add-another'>Add another</a> \
                    </div>"
                )
            })


            $(function() {
                $("#id_author").autocomplete({
                    source: "/authors/search_authors/",
                    minLength: 2,
                });
            });
            
        
        </script>
        
        <script>
        var mymap = new L.Map('mapid', {zoom: 2, center: new L.latLng([40,13]) });	//set center from first location
        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
            attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
            maxZoom: 18,
            id: 'mapbox.streets',
            accessToken: 'pk.eyJ1IjoiYnJpYW5jYWZmZXkiLCJhIjoiY2pkczJycjl5MmhqbTMzbzQ3bHJuaHA3aiJ9.cvRYYPNjQJVpFjdUcmIHzA'
        }).addTo(mymap);

        var markersLayer = new L.LayerGroup();
        mymap.addLayer(markersLayer);


        function addMarkerOnInputChange(lat, lng){

            markersLayer.clearLayers();
            
            var marker = new L.marker({'lat':lat,'lng':lng});
            markersLayer.addLayer(marker);
        }


        function addMarker(e){
            /* Function used to pic a pair
            of coordinates from the map. First, the layer
            is cleared which removes a point if it is in 
            the layer, then it adds the marker and updates
            form values based on the marker's lat and lng. */

            markersLayer.clearLayers();

            var marker = new L.marker(e.latlng);
            markersLayer.addLayer(marker);

            var lat = parseFloat(e.latlng["lat"]).toFixed(6)
            var lng = parseFloat(e.latlng["lng"]).toFixed(6)
            
            $("#id_lon").val(lat);
            $("#id_lat").val(lng);

            }

        mymap.on('click', function(e){
            addMarker(e);
        });


        $( "#id_lon" ).keyup(function() {
            var lon = $("#id_lon").val()
            var lat = $("#id_lat").val()
            addMarkerOnInputChange(lat,lon)
        });

        $( "#id_lat" ).keyup(function() {
            var lon = $("#id_lon").val()
            var lat = $("#id_lat").val()
            addMarkerOnInputChange(lat,lon)
        });

        </script>

        <input type="submit" class="btn btn-success" value="Add Book"/>
    </form>
    <br />
</div>

<script>
    $( document ).ready(function() {
        $( "#datepicker" ).datepicker();
    });
</script>

{% endblock %}